package common

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"errors"
)

func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

func PKCS5Unpadding(origData []byte, block cipher.Block) []byte {
	length := len(origData)
	unpadding := int(origData[length-1])
	if unpadding > block.BlockSize() {
		return nil
	}
	return origData[:(length - unpadding)]
}

func Encrypt(src []byte, key []byte) ([]byte, error) {
	if len(src) == 0 {
		return src, nil
	}

	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	bs := block.BlockSize()
	src = PKCS5Padding(src, bs)
	if len(src)%bs != 0 {
		return nil, errors.New("encrypt src length is error")
	}
	out := make([]byte, len(src))
	dst := out
	for len(src) > 0 {
		block.Encrypt(dst, src[:bs])
		src = src[bs:]
		dst = dst[bs:]
	}
	return out, nil
}
func Decrypt(src []byte, key []byte) ([]byte, error) {
	if len(src) == 0 {
		return src, nil
	}
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	out := make([]byte, len(src))
	dst := out
	bs := block.BlockSize()
	if len(src)%bs != 0 {
		return nil, errors.New("decrypt src length is error")
	}

	for len(src) > 0 {
		block.Decrypt(dst, src[:bs])
		src = src[bs:]
		dst = dst[bs:]
	}
	out = PKCS5Unpadding(out, block)

	return out, nil
}
